package com.zhou.basics.common.exception;

import com.alibaba.fastjson.JSON;
import com.zhou.basics.common.core.Result;
import com.zhou.basics.common.enums.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ProjectName: tsqingcheng
 * @ClassName: ExceptionHandler
 * @Time: 2020/2/26
 * @Author: zhou24
 * @Description: exception2的级别比exception高，所以最后的异常由exception2控制，若想此代码生效，注掉exception2即可
 * @Experience:
 */
@Component
public class ExceptionHandler implements HandlerExceptionResolver {
    static final Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handle, Exception ex) {
        System.out.println("====");
        Result result = new Result();
        if (ex instanceof ServiceException){
            result.setCode(ResultCode.SUCCESS).setMessage(ResultCode.SUCCESS.msg+"["+request.getMethod()+" "+request.getRequestURI()+"]");
        }
        if (ex instanceof NoHandlerFoundException){
            result.setCode(ResultCode.NOT_FOUND).setMessage(ResultCode.NOT_FOUND.msg+"["+request.getMethod()+" "+request.getRequestURI()+"]");
        }
        try {
            response.getWriter().write(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return null;
    }
}
